package com.daylightrobbery.server;
import com.daylightrobbery.server.handler.UdpServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class DaylightRobberApplicationServer implements  ApplicationListener<ContextRefreshedEvent>, Runnable {

    private static final Logger log = LoggerFactory.getLogger(DaylightRobberApplicationServer.class);

    @Autowired
    private UdpServerHandler udpServerHandler;

    private final int port = 7777;

    public void run(){
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) {
                            channel.pipeline().addLast(udpServerHandler);
                        }
                    });

            Channel ch = null;
            try {
                ch = b.bind(port).sync().channel();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("DaylightRobberApplication Server is ready and listening on " + port);

            // 等待服务socket关闭。
            try {
                ch.closeFuture().await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
         new Thread(this).start();
    }
}
